﻿using System;
using System.Data;
using TraditionalMalteseCuisine.App_Code.Functions;
using TraditionalMalteseCuisine.App_Code.Objects;
using TraditionalMalteseCuisine.App_Code.Operations;

namespace TraditionalMalteseCuisine
{
    public partial class Profile : System.Web.UI.Page
    {
        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetProfileDetails();

                if (CurrentProfile == null)
                    Response.Redirect("default.aspx");
            }
        }
        #endregion


        #region Events
        protected void cmbMaxLikedRecords_SelectedIndexChanged(object sender, EventArgs e)
        {
            MaxLikedRecords = int.Parse(cmbMaxLikedRecords.SelectedValue.ToString());
            BindMostRecentRecipes();
        }
        #endregion


        #region Buttons
        protected void btnSubscribe_Click(object sender, EventArgs e)
        {
            Site_Functions.AddSubscription(SubscriptionState);
            HandleSubscribeButton();
            BindMostRecentRecipes();
        }

        protected void btnUnsubscribe_Click(object sender, EventArgs e)
        {
            Site_Functions.RemoveSubscription(SubscriptionState);
            HandleSubscribeButton();
            BindMostRecentRecipes();
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            lblMessage.Visible = false;

            if (IsOwner)
            {
                if (txtCurrentPassword.Text.Length > 0)
                {
                    csvCurrentPassword.IsValid = (Hash_Functions.HashPassword(txtCurrentPassword.Text).Equals(CurrentProfile.Password));
                    csvPassword.IsValid = (txtPassword.Text.Length > 0);
                    csvPassword2.IsValid = (txtPassword2.Text.Length > 0);
                }
                else
                {
                    csvCurrentPassword.IsValid = true;
                    csvPassword.IsValid = true;
                    csvPassword2.IsValid = true;
                }

                if ((csvCurrentPassword.IsValid) && (csvPassword.IsValid) && (csvPassword2.IsValid))
                {
                    if ((!txtFirstName.Text.Equals(CurrentProfile.FirstName)) && (Site_Functions.UpdateSiteMember(CurrentProfile, SiteMember.FIRSTNAME_TAG, txtFirstName.Text)))
                        CurrentProfile.FirstName = txtFirstName.Text;

                    if ((!txtLastName.Text.Equals(CurrentProfile.LastName)) && (Site_Functions.UpdateSiteMember(CurrentProfile, SiteMember.LASTNAME_TAG, txtLastName.Text)))
                        CurrentProfile.LastName = txtLastName.Text;

                    if ((!cmbGender.SelectedValue.Equals(CurrentProfile.Gender)) && (Site_Functions.UpdateSiteMember(CurrentProfile, SiteMember.GENDER_TAG, cmbGender.SelectedValue)))
                        CurrentProfile.Gender = cmbGender.SelectedValue;

                    if (!txtEMail.Text.Equals(CurrentProfile.EMail))
                    {
                        csvEMailExists.IsValid = (!Site_Functions.DoesEmailExists(txtEMail.Text));

                        if ((csvEMailExists.IsValid) && (Site_Functions.UpdateSiteMember(CurrentProfile, SiteMember.EMAIL_TAG, txtEMail.Text)))
                            CurrentProfile.EMail = txtEMail.Text;
                    }

                    if ((txtCurrentPassword.Text.Length > 0) && (Site_Functions.UpdateSiteMember(CurrentProfile, SiteMember.PASSWORD_TAG, Hash_Functions.HashPassword(txtPassword.Text))))
                        CurrentProfile.Password = Hash_Functions.HashPassword(txtPassword.Text);

                    if (uplImageLocation.HasFile)
                    {
                        csvImageLocation.IsValid = Validation_Functions.IsValidImageFile(uplImageLocation.FileName);

                        if (csvImageLocation.IsValid)
                        {
                            if (!CurrentProfile.ImageLocation.Equals(SiteMember.DEFAULT_IMAGE_LOCATION))
                                IO_Functions.DeleteFile(Request.MapPath(CurrentProfile.ImageLocation));
                            if (!CurrentProfile.ThumbnailLocation.Equals(SiteMember.DEFAULT_THUMBNAIL_LOCATION))
                                IO_Functions.DeleteFile(Request.MapPath(CurrentProfile.ThumbnailLocation));

                            string newImageFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), uplImageLocation.FileName.Substring(uplImageLocation.FileName.LastIndexOf('.')));
                            string newImageLocation = string.Format("{0}{1}", SiteMember.DEFAULT_IMAGE_FOLDER_LOCATION, newImageFileName);
                            string newThumbnailLocation = string.Format("{0}{1}", SiteMember.DEFAULT_THUMBNAIL_FOLDER_LOCATION, newImageFileName);

                            string[] fieldnames = new string[] { SiteMember.IMAGE_LOCATION_TAG, SiteMember.THUMBNAIL_LOCATION_TAG };
                            string[] new_values = new string[] { newImageLocation, newThumbnailLocation };

                            if (Site_Functions.UpdateSiteMember(CurrentProfile, fieldnames, new_values))
                            {
                                CurrentProfile.ImageLocation = newImageLocation;
                                CurrentProfile.ThumbnailLocation = newThumbnailLocation;
                            }

                            Site_Functions.SaveImageFile(uplImageLocation, Request.MapPath(CurrentProfile.ImageLocation), Request.MapPath(CurrentProfile.ThumbnailLocation), 32);
                        }
                    }

                    ((MainMasterPage)Master).SiteMember = CurrentProfile;

                    lblMessage.Visible = true;
                }
            }
        }
        #endregion


        #region Methods
        protected string GetSubscriptionStatistics()
        {
            return Site_Functions.GetSubscriptionStatistics(SubscriptionState);
        }

        protected string GetTotalRecipesPosted()
        {
            return Site_Functions.GetTotalNumberOfRecipesPosted(CurrentProfile).ToString();
        }

        protected string GetContributionLevelForRecipesPosted()
        {
            return Site_Functions.GetAwardLevelForRecipesPosted(CurrentProfile);
        }

        protected string GetTotalRecipesCommentsPosted()
        {
            return Site_Functions.GetTotalNumberOfRecipesCommentsPosted(CurrentProfile).ToString();
        }

        protected string GetContributionLevelForRecipesCommentsPosted()
        {
            return Site_Functions.GetAwardLevelForRecipesCommentsPosted(CurrentProfile);
        }

        private void SetProfileDetails()
        {
            if ((ProfileID != null) && (ProfileID.Length > 0) && (Validation_Functions.IsNumeric(ProfileID)))
            {
                if (IsLoggedIn)
                {
                    if (((MainMasterPage)Master).SiteMember.ID.Equals(int.Parse(ProfileID)))
                    {
                        IsOwner = true;
                    }
                    else
                    {
                        SubscriptionState = new Subscription(((MainMasterPage)Master).SiteMember.ID, int.Parse(ProfileID));

                        HandleSubscribeButton();
                    }
                }

                if (IsOwner)
                {
                    CurrentProfile = ((MainMasterPage)Master).SiteMember;
                    DisplayDetails();
                }
                else
                {
                    CurrentProfile = GetSiteMemberDetails(int.Parse(ProfileID));
                    BindMostRecentRecipes();
                }

            }
        }

        private SiteMember GetSiteMemberDetails(int profileID)
        {
            return Site_Functions.GetSiteMemberByID(profileID);
        }

        private void DisplayDetails()
        {
            if (CurrentProfile != null)
            {
                txtFirstName.Text = CurrentProfile.FirstName;
                txtLastName.Text = CurrentProfile.LastName;
                txtEMail.Text = CurrentProfile.EMail;
                cmbGender.SelectedValue = CurrentProfile.Gender;
            }
        }

        private void HandleSubscribeButton()
        {
            btnSubscribe.Visible = (!Site_Functions.DoesSubscriptionExists(SubscriptionState));
            btnUnsubscribe.Visible = (!btnSubscribe.Visible);

            btnSubscribe.ToolTip = GetSubscriptionStatistics();
            btnUnsubscribe.ToolTip = btnSubscribe.ToolTip;
        }

        private void BindMostRecentRecipes()
        {
            try
            {
                DataTable dtRecipes = ReadOp.GetDataTable(Recipe.GetCommand_GetTopMostLikedRecipes(MaxLikedRecords, CurrentProfile.ID));

                cmbMaxLikedRecords.SelectedValue = MaxLikedRecords.ToString();

                dgvMostLiked.DataSource = dtRecipes;
                dgvMostLiked.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        #endregion


        #region Properties
        protected bool IsOwner
        {
            get { return ((ViewState["IsOwnProfile"] == null) ? false : (bool)ViewState["IsOwnProfile"]); }
            set { ViewState["IsOwnProfile"] = value; }
        }

        protected bool IsLoggedIn
        {
            get { return ((MainMasterPage)Master).IsLoggedIn; }
        }

        protected SiteMember CurrentProfile
        {
            get { return ((ViewState["CurrentProfile"] == null) ? null : (SiteMember)ViewState["CurrentProfile"]); }
            set { ViewState["CurrentProfile"] = value; }
        }

        protected Subscription SubscriptionState
        {
            get { return ((ViewState["subscription_state"] == null) ? null : (Subscription)ViewState["subscription_state"]); }
            set { ViewState["subscription_state"] = value; }
        }

        protected string ProfileID
        {
            get { return Request.Params["user"]; }
        }

        protected int MaxLikedRecords
        {
            get { return ((Session["MaxLikedRecords_InProfile"] == null) ? 3 : (int)Session["MaxLikedRecords_InProfile"]); }
            set { Session["MaxLikedRecords_InProfile"] = value; }
        }
        #endregion
    }
}